#include "hashtable.h"
#include <iostream>

AI_SOKOBAN::Hashtable::Hashtable()
{
    for(int i=0;i<size;i++)
    {
        table[i]  = NULL;
    }
}

void AI_SOKOBAN::Hashtable::add(const Level& level)
{
     int index = level.hash() % size;

    if(table[index] == NULL)
    {
        table[index] = new std::list<Level>();
        //table[index] = new std::list<int*>();
    }

    table[index]->push_back(level);
    //table[index]->push_back(level.getCompactData());
}

bool AI_SOKOBAN::Hashtable::contains(const Level& level)
{
     int index = level.hash() % size;
    //std::cout << "index = " << index << std::endl;
    if(table[index] == NULL)
    {
        return false;
    }

    std::list<Level>::const_iterator it;
    //std::list<int*>::const_iterator it;

    //int* compact_data = level.getCompactData();
    //int bits = level.getCols()*level.getRows()*2;
    //int ints = (bits % sizeof(int)*8 == 0) ? bits/sizeof(int)*8 : bits/sizeof(int)*8 + 1;

    for(it = table[index]->begin();it != table[index]->end();it++)
    {/*
        int* data = *it;
        bool matches = true;
        for(int i=0;i<ints;i++)
        {
            if(compact_data[i] != data[i])
            {
                matches = false;
                break;
            }
        }

        if(matches)
        {
            delete[] compact_data;
            return true;
        }*/
        
        if(*it == level)
        {
            return true;
        }
    }
    //delete[] compact_data;
    return false;
}

AI_SOKOBAN::Hashtable::~Hashtable()
{
    clear();
}

void AI_SOKOBAN::Hashtable::clear()
{
    for(int i=0;i<size;i++)
    {
        if(table[i] != NULL)
        {
            /*
            std::list<int*>::iterator it;
            for(it = table[i]->begin();it != table[i]->end();it++)
            {
                delete[] *it;
            }*/
            delete table[i];
            table[i] = NULL;
        }
    }
}